import { getToken } from "@/utils/cookie";
import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "/",
      redirect: "/login",
    },
    {
      path: "/layout",
      name: "layout",
      component: () => import("@/views/Layout.vue"),
      children: [
        {
          path: "question",
          name: "question",
          component: () => import("@/views/Question.vue"),
        },
        {
          path: "exam",
          name: "exam",
          component: () => import("@/views/Exam.vue"),
        },
        {
          path: "cuser",
          name: "cuser",
          component: () => import("@/views/Cuser.vue"),
        },
        {
          path: "updateExam",
          name: "updateExam",
          component: () => import("@/views/UpdateExam.vue"),
        },
      ],
    },
  ],
});

//全局路由规则配置
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === "/login") {
      next({
        path: "/layout",
      });
    } else {
      next();
    }
  } else {
    if (to.path !== "/login") {
      next({
        path: "/login",
      });
    } else {
      next();
    }
  }
});

export default router;
